package com.credithc.signature.core.ro;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhanghanqiu181212@credithc.com
 * @Date 2020/1/9 10:55
 */
@Data
public class JsonField {
    //digsign账户 *
    private String userid = "adminidana@tandatanganku.com";
    //地址*
    private String alamat = "Jawa Barat/Bogor/Ciampea/Bojong Rangkas";
    //性别 Laki-laki标识男，Perempuan标识女 *
    private String jenisKelamin = "perempuan";
    //区*
    private String kecamatan="Cipinang Besar Selatan";
    //区的下一级*
    private String kelurahan="Jatinegara";
    //邮编*
    private String kodepos="13410";
    //城市*
    private String kota="DKI Jakarta";
    //姓名*
    private String name="PingTait1";
            //"ayu sari yulinda";
    //电话号码*
    private String tlp="081310508151";
    //出生日期*
    private String tglLahir="07-22-1986";
    //省*
    private String provinci="DKI Jakarta";
    //身份证号 *
    private String idktp = "140603199205049968";
            //"3173046810920001";
            //"1271205805950006";
    //出生地*
    private String tmpLahir ="tangerang";
    //邮箱*
    private String email="idana2@tandatanganku.com";
    //税卡号
    private String npwp = "";
            //"75.444.097.9-445.000";

    private Boolean redirect = true;


    public String getJsonString(){
        Map map = new HashMap();
        Map mapw = new HashMap();
        map.put("userid",userid);
        map.put("alamat",alamat);
        map.put("jenis_kelamin", jenisKelamin);
        map.put("kecamatan",kecamatan);
        map.put("kelurahan",kelurahan);
        map.put("kode-pos",kodepos);
        map.put("kota",kota);
        map.put("nama",name);
        map.put("tlp",tlp);
        map.put("tgl_lahir", tglLahir);
        map.put("email",email);
        map.put("npwp", npwp);
        map.put("redirect",redirect);
        map.put("provinci",provinci);
        map.put("idktp",idktp);
        map.put("tmp_lahir", tmpLahir);
        mapw.put("JSONFile",map);
        return JSONObject.toJSONString(mapw);
    }


    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization","Bearer SIpwZa7RQaft69V2eu4H5IU47eJTspmj3zrpiCUtu8aU6SY7Dl6W1A6XcQGgit");
        //注册请求
       /* String url = "https://api.tandatanganku.com/REG-MITRA.html";
        MultiValueMap<String,Object> map= new LinkedMultiValueMap<>();
        JsonField jsonField = new JsonField();
        FileSystemResource fotoktp = new FileSystemResource("E:/myProject/fotoktp.png");
        FileSystemResource fotodiri = new FileSystemResource("E:/myProject/fotodiri.png");
        // FileSystemResource Fotonpwp = new FileSystemResource("E:/myProject/Fotonpwp.png");
        map.add("jsonfield",jsonField.getJsonString());
        System.out.println("注册请求参数：   "+jsonField.getJsonString());
        map.add("fotoktp",fotoktp);
        map.add("fotodiri",fotodiri);
        map.add("ttd","" );
        map.add("Fotonpwp","");
        HttpEntity<MultiValueMap> request = new HttpEntity(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
        System.out.println(response.getBody());*/
        //激活请求
   /*     MultiValueMap<String,Object> param= new LinkedMultiValueMap<>();
        Map jh = new HashMap();
        Map jhn = new HashMap();
        String jhUrl = "https://api.tandatanganku.com/gen/genACTPage.html";
        jhn.put("userid","adminidana@tandatanganku.com");
        jhn.put("email_user","idana8@tandatanganku.com");
        jh.put("JSONFile",jhn);
        param.add("jsonfield",JSONObject.toJSONString(jh));
        System.out.println("激活请求参数：    "+JSONObject.toJSONString(jh));
        HttpEntity<MultiValueMap> request = new HttpEntity(param, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( jhUrl, request , String.class );
        System.out.println(response.getBody());*/
       //发送文档接口
       /* String sendUrl = "https://api.tandatanganku.com/SendDocMitraAT.html";
        MultiValueMap<String,Object> sendParam= new LinkedMultiValueMap<>();
        FileSystemResource sendPdf = new FileSystemResource("E:/myProject/ht.pdf");
        String sendStr = "{\n" +
                "    \"JSONFile\": {\n" +
                "        \"userid\": \"adminidana@tandatanganku.com\",\n" +
                "        \"document_id\": \"test1-11\",\n" +
                "        \"payment\": \"3\",\n" +
                "        \"redirect\": true,\n" +
                "  \"sequence_option\": true,   "+
                "        \"send-to\": [\n" +
                "            {\n" +
                "                \"name\": \"Stacia Angela\",\n" +
                "                \"email\": \"idana1@tandatanganku.com\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"req-sign\": [\n" +
                "            {\n" +
                "                \"name\": \"ayu sari yulinda\",\n" +
                "                \"email\": \"idana22@tandatanganku.com\",\n" +
                "                \"aksi_ttd\": \"mt\",\n" +
                "              \n" +

                "                \"page\": \"21\",\n" +
                "                \"llx\": \"50\",\n" +
                "                \"lly\": \"50\",\n" +
                "                \"urx\": \"100\",\n" +
                "                \"ury\": \"100\",\n" +
                "                \"visible\": \"1\"\n," +
                "\"signing_seq\" : 1 "+
                "            },\n" +
                "            {\n" +
                "                \"name\": \"PingTait\",\n" +
                "                \"email\": \"idana9@tandatanganku.com\",\n" +
                "                \"aksi_ttd\": \"at\",\n" +
                "\"kuser\" : \"V3klguOVvWJH3eET\" ,"+
                "              \n" +

                "                \"page\": \"21\",\n" +
                "                \"llx\": \"410\",\n" +
                "                \"lly\": \"50\",\n" +
                "                \"urx\": \"600\",\n" +
                "                \"ury\": \"100\",\n" +
                "                \"visible\": \"1\"\n," +
                "\"signing_seq\" : 1 "+
                "            },\n" +
                "            {\n" +
                "                \"name\": \"YongHui zhang\",\n" +
                "                \"email\": \"idana44@tandatanganku.com\",\n" +
                "                \"aksi_ttd\": \"mt\",\n" +
                "              \n" +
                "                \"page\": \"21\",\n" +
                "                \"llx\": \"200\",\n" +
                "                \"lly\": \"50\",\n" +
                "                \"urx\": \"400\",\n" +
                "                \"ury\": \"100\",\n" +
                "                \"visible\": \"1\"\n," +
                "\"signing_seq\" : 2 "+
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "}";
        sendParam.add("jsonfield",sendStr);
        sendParam.add("file",sendPdf);
        HttpEntity<MultiValueMap> request = new HttpEntity(sendParam, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( sendUrl, request , String.class );
        System.out.println(response.getBody());*/
        //签章接口
       /* String signUrl = "https://api.tandatanganku.com/gen/genSignPage.html";
        MultiValueMap<String,Object> signParam= new LinkedMultiValueMap<>();
        String signStr = "{\n" +
                "    \"JSONFile\": {\n" +
                "        \"userid\": \"adminidana@tandatanganku.com\",\n" +
                "        \"document_id\": \"test1-11\",\n" +
                "        \"email_user\": \"idana1@tandatanganku.com\",\n" +
                "\t\"view_only\":false\n" +
                "       \n" +
                "    }\n" +
                "}";
        signParam.add("jsonfield",signStr);
        HttpEntity<MultiValueMap> request = new HttpEntity(signParam, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( signUrl, request , String.class );
        System.out.println(response.getBody());*/

      //下载接口
    /*    String downUrl = "https://api.tandatanganku.com/DWMITRA.html";
        MultiValueMap<String,Object> downParam= new LinkedMultiValueMap<>();
        String downStr = "{\"JSONFile\":\n" +
                "{\n" +
                "\"userid\": \"adminidana@tandatanganku.com\",\n" +
                "\"document_id\": \"202001151632\"\n" +
                "}\n" +
                "}";
        downParam.add("jsonfield",downStr);
        //HttpEntity<MultiValueMap> request = new HttpEntity(downParam, headers);
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        ResponseEntity<byte[]> response = restTemplate.postForEntity( downUrl, httpEntity , byte[].class );
//        ResponseEntity<byte[]> response = restTemplate.exchange(downUrl, HttpMethod.POST,
//                httpEntity, byte[].class);
       // System.out.println(response.getBody());
        System.out.println("===状态码================");
        System.out.println(">> "+ response.getStatusCodeValue());
        System.out.println("===返回信息================");
        System.out.println(">> "+ response.getHeaders().getContentType());
        System.out.println(">> "+ response.getHeaders().getContentType().getSubtype());
        try {
            File di = new File("E:/myProject/");
            File file = File.createTempFile("ess-", "." + response.getHeaders().getContentType().getSubtype(),di);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(response.getBody());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

    //下载接口base64

/*        String b64Url ="https://api.tandatanganku.com/DWMITRA64.html" ;
        MultiValueMap<String,Object> downParam= new LinkedMultiValueMap<>();
        String downStr = "{\"JSONFile\":\n" +
                "{\n" +
                "\"userid\": \"adminidana@tandatanganku.com\",\n" +
                "\"document_id\": \"test1-3\"\n" +
                "}\n" +
                "}";
        downParam.add("jsonfield",downStr);
        HttpEntity<MultiValueMap> request = new HttpEntity(downParam, headers);
       // HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        ResponseEntity<String> response = restTemplate.postForEntity( b64Url, request , String.class );
        System.out.println(response.getBody());
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        String file = jsonObject.getString("JSONFile");
        JSONObject jsonObject1 = JSONObject.parseObject(file);
        decode(jsonObject1.getString("file"), UUID.randomUUID() +"test1-4.pdf","E:/myProject/");*/

    //批量签章
     /*   String plUrl = "https://api.tandatanganku.com/gen/genBulkSign.html";
        MultiValueMap<String,Object> plParam= new LinkedMultiValueMap<>();
        String plStr = "{\n" +
                "    \"JSONFile\": {\n" +
                "        \"userid\": \"adminidana@tandatanganku.com\",\n" +
                "        \"email_user\": \"idana5@tandatanganku.com\",\n" +
                "\t\"must_read\":false\n ," +
                "        \"document_id\": [\n" +
                "            \"test1-3\",\n" +
                "            \"test1-2\"\n" +
                "        ]\n" +
                "    }\n" +
                "}";
        plParam.add("jsonfield",plStr);
        plParam.add("file",plStr);
        HttpEntity<MultiValueMap> request = new HttpEntity(plParam, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( plUrl, request , String.class );
        System.out.println(response.getBody());*/
    }



    public static byte[] decode(String base64Str,String fileName,String filePath){
        File file = null;
        //创建文件目录
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;

        byte[] b = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            b = decoder.decodeBuffer(replaceEnter(base64Str));
            //window
            //file=new File(filePath+"\\"+fileName);
            //linux
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(b);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return b;
    }

    /**
     * 图片转字符串
     * @param image
     * @return
     */
    public static String encode(byte[] image){
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    public static String encode(String uri){
        BASE64Encoder encoder = new BASE64Encoder();
        return replaceEnter(encoder.encode(uri.getBytes()));
    }

    /**
     *
     * @path    图片路径
     * @return
     */

    public static byte[] imageTobyte(String path){
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while((numBytesRead = input.read(buf)) != -1){
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public static String replaceEnter(String str){
        String reg ="[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

}


